package com.hq.ims.data.service;

import com.hq.ims.data.dao.PermissionMapRoleUserMapper;
import com.hq.ims.data.entity.Company;
import com.hq.ims.data.entity.PermissionMapRoleUser;
import com.hq.ims.data.entity.User;
import com.hq.ims.data.utils.ErrMsgConstant;
import com.hq.ims.data.vo.PermissionMapRoleUserMapstruct;
import com.hq.mybatis.base.BaseService;
import com.hq.utils.util.BooleanUtils;
import com.hq.utils.util.ListUtils;
import com.hq.utils.util.ObjectUtils;
import com.hq.web.utils.SpringBootValidateUtils;
import lombok.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * jiang bai ping
 *
 * @Email 526666031@qq.co
 * @Detail 角色-角色映射表服务实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BasePermissionMapRoleUserService extends BaseService<PermissionMapRoleUserMapper, PermissionMapRoleUser> {

    @Resource
    private BaseCompanyService baseCompanyService;
    @Resource
    private BaseUserService baseUserService;
    @Resource
    private BaseCompanyEmployeeService baseCompanyEmployeeService;


    /**
     * 对映射关系进行校验
     */
    public boolean isExistsUserRole(
            @NonNull String userId,
            @NonNull String companyId,
            @NonNull String roleId
    ) {
        return this.lambdaQuery()
                .eq(PermissionMapRoleUser::getPermissionRoleId, roleId)
                .eq(PermissionMapRoleUser::getUserId, userId)
                .eq(PermissionMapRoleUser::getCompanyId, companyId)
                .count() > 0;
    }


    /**
     * 删除数据
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean delByRoleIdAndCompanyId(
            @NonNull String roleId,
            @NonNull String companyId
    ) {
        return this.lambdaUpdate()
                .eq(PermissionMapRoleUser::getPermissionRoleId, roleId)
                .eq(PermissionMapRoleUser::getCompanyId, companyId)
                .remove();
    }

    /**
     * 删除数据
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean delByUserIdAndCompanyId(
            @NonNull String userId,
            @NonNull String companyId
    ) {
        return this.lambdaUpdate()
                .eq(PermissionMapRoleUser::getUserId, userId)
                .eq(PermissionMapRoleUser::getCompanyId, companyId)
                .remove();
    }


    /**
     * 绑定用户角色
     */
    @Transactional(rollbackFor = Exception.class)
    public void bindUserRole(
            PermissionMapRoleUserMapstruct.BindUserRoleVo saveVo
    ) {
        //1.清除之前的数据 根据用户的公司id
        this.delByUserIdAndCompanyId(saveVo.getUserId(), saveVo.getCompanyId());
        //2: 添加用户&角色绑定关系
        SpringBootValidateUtils.validate(saveVo);

        //用户是否存在
        User user = baseUserService.getById(saveVo.getUserId());
        ObjectUtils.isNullThrow(user, ErrMsgConstant.USER_INFO_NOT_EXISTS);
        //公司是否存在
        Company company = baseCompanyService.getById(saveVo.getCompanyId());
        ObjectUtils.isNullThrow(company, ErrMsgConstant.COMPANY_INFO_NOT_EXISTS);
        //是否公司员工
        boolean isExistsCompanyUser = baseCompanyEmployeeService.userIsJoinCompany(saveVo.getUserId(), saveVo.getCompanyId(), null);
        BooleanUtils.isFalseThrow(isExistsCompanyUser, ErrMsgConstant.USER_IS_NOT_COMPANY_EMPLOYEE);

        //添加角色
        List<String> ddistinctRoleIdList = saveVo.getPermissionRoleIdList().stream().distinct().collect(Collectors.toList());
        List<PermissionMapRoleUser> saveList = new ArrayList<>(ddistinctRoleIdList.size());
        for (String roleId : ddistinctRoleIdList) {
            PermissionMapRoleUser permissionMapRoleUser = new PermissionMapRoleUser();
            saveList.add(permissionMapRoleUser);
            permissionMapRoleUser.setUserId(saveVo.getUserId());
            permissionMapRoleUser.setPermissionRoleId(roleId);
            permissionMapRoleUser.setCompanyId(saveVo.getCompanyId());
        }

        if (ListUtils.isExistsEle(saveList)) {
            this.saveBatch(saveList);
        }
    }

    //----------------------------- 获取 -----------------------------------

    @Transactional(rollbackFor = Exception.class)
    public List<PermissionMapRoleUser> getByUserIdAndCompanyId(
            @NonNull String userId,
            @NonNull String companyId
    ) {
        List<PermissionMapRoleUser> list = this.lambdaQuery()
                .eq(PermissionMapRoleUser::getUserId, userId)
                .eq(PermissionMapRoleUser::getCompanyId, companyId)
                .list();
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public List<PermissionMapRoleUser> getByRoleIdAndCompanyId(
            @NonNull String roleId,
            @NonNull String companyId
    ) {
        List<PermissionMapRoleUser> list = this.lambdaQuery()
                .eq(PermissionMapRoleUser::getPermissionRoleId, roleId)
                .eq(PermissionMapRoleUser::getCompanyId, companyId)
                .list();
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public List<String> getRoleIdByUserIdAndCompanyId(
            @NonNull String userId,
            @NonNull String companyId
    ) {
        List<PermissionMapRoleUser> list = this.lambdaQuery()
                .select(PermissionMapRoleUser::getPermissionRoleId)
                .eq(PermissionMapRoleUser::getUserId, userId)
                .eq(PermissionMapRoleUser::getCompanyId, companyId)
                .list();
        if (ListUtils.isNotExistsEle(list)) {
            return ListUtils.newEmptyList();
        }
        List<String> roleIdList = list.stream().map(PermissionMapRoleUser::getPermissionRoleId).distinct().collect(Collectors.toList());
        return roleIdList;
    }

    @Transactional(rollbackFor = Exception.class)
    public List<String> getUserIdByRoleIdAndCompanyId(
            @NonNull String roleId,
            @NonNull String companyId
    ) {
        List<PermissionMapRoleUser> list = this.lambdaQuery()
                .select(PermissionMapRoleUser::getUserId)
                .eq(PermissionMapRoleUser::getPermissionRoleId, roleId)
                .eq(PermissionMapRoleUser::getCompanyId, companyId)
                .list();
        if (ListUtils.isNotExistsEle(list)) {
            return ListUtils.newEmptyList();
        }
        List<String> roleIdLIst = list.stream().map(PermissionMapRoleUser::getUserId).distinct().collect(Collectors.toList());
        return roleIdLIst;
    }

    @Transactional(rollbackFor = Exception.class)
    public void delByCompanyId(String companyId) {
        this.lambdaUpdate().eq(PermissionMapRoleUser::getCompanyId, companyId).remove();
    }
}
